package com.crazymaker.springcloud.websocket.gateway;

import com.crazymaker.springcloud.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.*;

import static com.crazymaker.push.platform.contract.constants.PushConstants.WEBSOCKET_PROVIDER_HEALTH_URI;
import static com.crazymaker.springcloud.common.util.HttpRequestUtil.simpleGet;
import static com.crazymaker.springcloud.common.util.HttpRequestUtil.simplePost;

@Slf4j
public class UpdateCases {


    @Test
 public    void testUpdateServer() {


        List<String> list = Collections.singletonList("192.168.56.1:9999");


        //节点按照编号，升序排列
        Collections.sort(list);
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            String url = "http://" + next.split(":")[0] + WEBSOCKET_PROVIDER_HEALTH_URI;
            log.info("url is : {}", url);
            try {
                String responce = simpleGet(url);
                if (null != responce && StringUtils.isNotEmpty(responce)) {
                    continue;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            iterator.remove();
        }

        if (null == list || list.size() <= 0) {
            log.error("websocket server list is null");
            return;
        }

        Map<String, String> data = new HashMap<>();
        int index = 0;
        for (String item : list) {
            data.put("server" + index++, item);
        }
        data.put("serverCount", String.valueOf(index));
       String  params=JsonUtil.pojoToJson(data);

        String websocketRegisterGateway = "cdh2:8000";
        String url ="http://"+ websocketRegisterGateway+"/";
        try {
            String res = simplePost(url, params);
            log.info("websocket gateway {} update ok,{}", websocketRegisterGateway, res);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("websocket gateway  update false,{}", url);

    }
}
